package com.weige.elefence.http;

import com.alibaba.fastjson.JSONObject;
import com.weige.elefence.dto.R;
import com.weige.elefence.utils.ReadJsonFileUtil;
import com.weige.elefence.utils.WebApplicationUtils;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.ext.web.Router;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author ltj
 * @Description WEB服务
 * @date 2022/5/23
 */
public class WebServer {
    private static final Logger log = LoggerFactory.getLogger(WebServer.class);

    private static void init() {

        Vertx vertx = Vertx.vertx();
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);
        router.route().handler(handler -> {
            HttpServerRequest request = handler.request();

            HttpServerResponse response = handler.response();
            // 设置response返回的格式
            response.putHeader("content-type", "application/json;charset=UTF-8");
            // 获取请求路径
            String path = request.path();
            log.info("请求路径：" + path);
            try {
                String[] split = path.split("/");
                if (split.length > 1) {
                    boolean b = WebApplicationUtils.CLASS_MAP.containsKey(split[1]);
                    if (!b) {
                        response.end(JSONObject.toJSONString(R.error(404,"找不到路径")));
                        return;
                    }
                    Object object = WebApplicationUtils.OBJ_MAP.get(split[1]);
                    if (split.length > 2) {
                        Method method = object.getClass().getDeclaredMethod(split[2]);
                        if (Objects.isNull(method)) {
                            response.end(JSONObject.toJSONString(R.error(404,"找不到路径")));
                            return;
                        }
                        // 反射注入方法
                        List<Map.Entry<String, String>> entries = request.params().entries();
                        List<Object> list = new ArrayList<>();
                        for (Map.Entry<String, String> entry : entries) {
                            list.add(entry.getValue());
                        }
                        Object invoke = method.invoke(object, list.toArray());
                        if (invoke instanceof R){
                            response.end(JSONObject.toJSONString(invoke));
                            return;
                        }
                        response.end(invoke.toString());
                    }
                }
            } catch (InvocationTargetException | IllegalAccessException e) {
                response.end(JSONObject.toJSONString(R.error(404,"找不到路径")));
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        });
        String port = ReadJsonFileUtil.map.get("server-port");
        server.requestHandler(router).listen(Integer.parseInt(port));
        log.info("server-port:" + port);
    }

    public static void run() {
        WebServer.init();
    }
}
